package com.open.web.config;

import com.open.web.filter.TraceParentHandler;
import com.open.web.interceptor.RequestInterceptor;
import com.open.web.interceptor.RequestTimeInterceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Resource;

/**
 * WebConfig
 */
@Configuration
public class WebConfig implements WebMvcConfigurer , CommandLineRunner {

    private static final Logger log = LoggerFactory.getLogger(WebConfig.class);
    @Value("${swagger.enable:true}")
    private Boolean swaggerEnable;

    @Resource
    private TraceParentHandler traceParentHandler;
    @Resource
    private RequestInterceptor requestInterceptor;
    @Resource
    private RequestTimeInterceptor requestTimeInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(traceParentHandler)
                .addPathPatterns("/**");

        registry.addInterceptor(requestInterceptor)
                .addPathPatterns("/**");

        // registry.addInterceptor(requestTimeInterceptor)
        //         .addPathPatterns("/**");
    }

    /**
     * 配置出参content-type默认为application/json;charset=UTF-8
     */
    @Override
    public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
        configurer.defaultContentType(MediaType.APPLICATION_JSON);
    }

    /**
     * addResourceHandlers
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        if (swaggerEnable) {
            registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
            registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
        }
    }

    /**
     * Callback used to run the bean.
     *
     * @param args incoming main method arguments
     * @throws Exception on error
     */
    @Override
    public void run(final String... args) throws Exception {
        log.info("WebConfig init success.");
    }
}